package com.mmall.service.impl;

import com.github.pagehelper.StringUtil;
import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.MD5Util;
import net.sf.jsqlparser.schema.Server;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * Created by Administrator on 2018/11/7.
 */
@Service(value = "iUserServiceImpl")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ServerResponse<User> login(String username, String password) {
//        根据用户名查询出用户并返回结果
        int resultCount = userMapper.checkUsername(username);
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("用户不存在！");
        }
        //todo 密码登陆MD5
        String md2Password = MD5Util.MD5EncodeUtf8(password);
//        根据用户名和密码查询用户信息
        User user = userMapper.selectLogin(username, md2Password);
        if (user == null) {
            return ServerResponse.createByErrorMessage("密码错误！");
        }
//        密码错误后，将密码置为空
        user.setPassword(StringUtils.EMPTY);
//        返回结果
        return ServerResponse.createBySuccess("登陆成功！", user);
    }

    public ServerResponse<String> register(User user) {
//        注册的时候 首先要验证用户名是否存在
//        int resultCount = userMapper.checkUsername(user.getUsername());
//        if (resultCount > 0) {
//            return ServerResponse.createByErrorMessage("用户名已存在");
//        }

//        调用封装的验证方法
        ServerResponse validResponse = this.checkValid(user.getUsername(), Const.USERNAME);
        if (!validResponse.isSuccess()) {
            return validResponse;
        }

//        验证邮箱，跟上面方式一样
        validResponse = this.checkValid(user.getEmail(), Const.EMAIL);
        if (!validResponse.isSuccess()) {
            return validResponse;
        }

//        设置角色
        user.setRole(Const.Role.ROLE_CUSTOMER);
//        MD5对密码加密存储
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));

        int resultCount = userMapper.insert(user);
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createBySuccessMessage("注册成功");
    }

    public ServerResponse<String> checkValid(String str, String type) {
//        判断类型，存在，则对其值进行判断
        if (StringUtils.isNotBlank(type)) {
            if (Const.USERNAME.equals(type)) {
                int resultCount = userMapper.checkUsername(str);
                if (resultCount > 0) {
                    return ServerResponse.createByErrorMessage("用户名已存在");
                }
            }
            if (Const.EMAIL.equals(type)) {
                int resultCount = userMapper.checkEmail(str);
                if (resultCount > 0) {
                    return ServerResponse.createByErrorMessage("email已存在");
                }
            }
        } else {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }

    //    查询密保问题
    public ServerResponse selectQuestion(String username) {
//        判断username是否存在
        ServerResponse validResponse = this.checkValid(username, Const.USERNAME);
//        如果用户名不存在，则返回
        if (validResponse.isSuccess()) {
            return ServerResponse.createByErrorMessage("用户不存在");
        }
//        如果用户存在，则查询
        String question = userMapper.selectQuestionByUsername(username);
        if (StringUtils.isNotBlank(question)) {
            return ServerResponse.createBySuccess(question);
        }
        return ServerResponse.createByErrorMessage("密保问题为空");
    }

    //    校验密保问题的方法
    public ServerResponse<String> checkAnswer(String username, String question, String answer) {
////        首先判断用户名是否存在，
//        ServerResponse validUsername = this.checkValid(username, Const.USERNAME);
//        if (validUsername.isSuccess()){
//            return ServerResponse.createByErrorMessage("用户不存在");
//        }
////        用户存在的情况
//        String quest = userMapper.selectQuestionByUsername(username);
////        如果存在密保问题，则比对用户回答
//        if (quest != null){
//            if (answer.equals(quest)){
//                return ServerResponse.createBySuccessMessage("验证通过");
//            }else {
//                return ServerResponse.createByErrorMessage("验证失败");
//            }
//        }else {
//            return ServerResponse.createByErrorMessage("密保问题为空");
//        }
        int resultCount = userMapper.checkAnswer(username, question, answer);
        if (resultCount > 0) {
//            如果resultCount大于零，说明这个密保问题回答正确，此时我们需要做的是
//            生成UUID
            String forgetToken = UUID.randomUUID().toString();
//            设置本地缓存
            TokenCache.setKey(TokenCache.TOKEN_PREFIX + username, forgetToken);
//            返回这个forgetToken
            return ServerResponse.createBySuccess(forgetToken);
        }
        return ServerResponse.createByErrorMessage("问题答案错误");
    }

    //    忘记密码
    public ServerResponse<String> forgetResetPassword(String username, String passwordNew, String forgetToken) {
//        校验参数
        if (StringUtils.isBlank(forgetToken)) {
            return ServerResponse.createByErrorMessage("Token不能为空");
        }
//        校验username
        ServerResponse validResponse = this.checkValid(username, Const.USERNAME);
        if (validResponse.isSuccess()) {
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX + username);
//        判断token是否存在
        if (StringUtils.isBlank(token)) {
            return ServerResponse.createByErrorMessage("token无效或过期");
        }
//        上述token判断通过后，判断新密码
        if (StringUtils.equals(forgetToken, token)) {
//            对新密码进行加密处理
            String MD5PasswordNew = MD5Util.MD5EncodeUtf8(passwordNew);
//            把新密码更新进用户信息
            int resultCount = userMapper.updatePasswordByUsername(username, MD5PasswordNew);
            if (resultCount > 0) {
                return ServerResponse.createBySuccessMessage("更新密码成功");
            }
        } else {
            return ServerResponse.createByErrorMessage("token错误，请重新获取重置密码的token");
        }
        return ServerResponse.createByErrorMessage("修改密码失败");
    }

    //    登陆状态下，重置密码
    public ServerResponse<String> resetPassword(String passwordOld, String passwordNew, User user) {
//        为防止横向越权，要校验用户旧密码，确定是这个用户的旧密码
        int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld), user.getId());
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("旧密码错误");
        }
//        上面验证通过后将新密码更新进用户信息
        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if (updateCount > 0) {
            return ServerResponse.createBySuccessMessage("密码更新成功");
        }
        return ServerResponse.createByErrorMessage("密码更新失败");
    }

    //    获取当前用户信息
    public ServerResponse<User> getInformation(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }
//        把查出来的用户信息中密码置空后返回
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }

    public ServerResponse<User> updateInformation(User user) {
        int resultCount = userMapper.checkEmailByUserId(user.getEmail(), user.getId());
        if (resultCount > 0) {
            return ServerResponse.createByErrorMessage("email已蠢仔，请更换email再进行更新");
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());

        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if (updateCount > 0) {
            return ServerResponse.createBySuccess("更新个人信息成功", updateUser);
        }
        return ServerResponse.createByErrorMessage("更新个人信息失败");
    }

    public ServerResponse checkAdminRole(User user){
        if (user != null && user.getRole().intValue() == Const.Role.ROLE_ADMIN){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }


}
